import { defineStore } from "pinia"
import { getCartList, deleteCartList, putCartList } from "@/api/index.js"
export const useCart = defineStore('cartStore', {
    state: () => {
        return {
            cartList: []
        }
    },
    actions: {
        // 给购物车中的每一俄国商品添加checked选项
        changeCartList(list) {
            this.cartList = list.map(item => {
                item.checked = true
                return item
            })
        },
        // 获取商品数据
        getCartListAsync() {
            // 发送ajax请求
            getCartList().then(data => {
                this.changeCartList(data.data || [])
            })
        },
        // 删除购物车中的商品
        async deleteCartListAsync(id) {
            let res = await deleteCartList(id);
            if (res.resultCode === 200) {
                this.getCartListAsync()
            }
        },
        async putCart(cartItemId, goodsCount) {
            let res = await putCartList(cartItemId, goodsCount)
            if (res.resultCode === 200) {
                this.getCartListAsync()
            }
        }
    },
    getters: {
        cartNum() {
            return this.cartList.reduce((prev, next) => {
                return prev + next.goodsCount;
            }, 0)
        },
    }
})